<?php

namespace App\Http\Middleware\Auth;

use App\Http\Services\LoginService;
use App\Models\Member;
use App\Models\Minilogin;
use App\Repositories\ContactRepository;
use Closure;

class MiniappLogin
{
    /**
     * 小程序登录验证
     */
    public function handle($request, Closure $next)
    {
        //防止非接口调用
        if (!$request->get("use", 0) && !preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"])) {
            return retFail("请求失败");
        }

        $token = $request->header('token');
        if (empty($token)) {
            return response([
                'code' => 401,
                'msg' => '权限不足',
                'data' => []
            ], 401);
        }

        $login = new LoginService();
        $adminId = $login->authcode($token, 'DECODE');

        if (empty($adminId)) {
            return response([
                'code' => 401,
                'msg' => '无效的Token',
                'data' => []
            ], 401);
        }

        define("IS_VISUAL", 0);//模拟账号
        // 模拟用户登录
        $minilogin = Minilogin::where(['uid' => $adminId])->first();
        if (!empty($minilogin) && !empty($minilogin['df_uid']) && date('Y-m-d H:i:s', strtotime('+20 Minute', strtotime($minilogin['update_time']))) > date('Y-m-d H:i:s')) {
            $adminId = $minilogin['df_uid'];
            define("IS_VISUAL", 1);//模拟账号
        }

        $request->offsetSet('wechat_admin_id', $adminId);
        if ($adminId) {
            define("UID", $adminId);
        }

        $ip = request()->ip();
        $reg_ip = Member::where("id", "=", $adminId)->value('reg_ip');
        if (empty($reg_ip)) {
            $data['reg_ip'] = $ip;
        }

        $data['last_login_time'] = time();
        $data['last_login_ip'] = $ip;

        //记录用户最后访问时间
        Member::where("id", "=", $adminId)->update($data);

        return $next($request);
    }

}
